package com.mcj.tokendemo.service.impl;

import com.mcj.tokendemo.entity.LoginUser;
import com.mcj.tokendemo.entity.ResponseResult;
import com.mcj.tokendemo.entity.User;
import com.mcj.tokendemo.service.LoginService;
import com.mcj.tokendemo.util.JwtUtil;
import com.mcj.tokendemo.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {
	
	@Autowired
	private AuthenticationManager authenticationManager;
	
	@Autowired
	private RedisCache redisCache;
	
	@Override
	public ResponseResult login(User user) {
		// AuthenticationManager authenticate 进行用户认证
		UsernamePasswordAuthenticationToken authenticationToken =
				new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
		Authentication authenticate = authenticationManager.authenticate(authenticationToken);
		// 如果没有通过认证，给出相应的提示，抛出异常
		if (Objects.isNull(authenticate)) {
			throw new RuntimeException("登录失败");
		}
		// 认证通过，使用userId生成jwt
		LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
		String userId = loginUser.getUser().getId().toString();
		String jwt = JwtUtil.createJWT(userId);
		Map<String, String> map = new HashMap<>();
		map.put("token", jwt);
		// 把完整的用户信息存入redis，userId为key
		redisCache.setCacheObject("login:" + userId, loginUser);
		
		return new ResponseResult(200, "登陆成功", map);
	}
	
	@Override
	public ResponseResult logout() {
		// 获取SecurityContextHolder中的用户id
		UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
		LoginUser loginUser = (LoginUser) authentication.getPrincipal();
		Long userId = loginUser.getUser().getId();
		// 删除redis中的值
		redisCache.deleteObject("login:" + userId);
		return new ResponseResult(200, "注销成功");
	}
	
}
